<template>
  <div class="header-oper">
    <div class="header-left">
      <!-- 添加 -->
      <el-dropdown class="drop-btn">
        <el-button>
          <i class="iconfont icon-icon-test"></i>
          {{ $t("operations.add") }}
        </el-button>
        <template #dropdown>
          <el-dropdown-menu placement="bottom-start">
            <el-dropdown-item @click.native="openDialog('primitive', 'add')">
              {{ $t("operations.primitive") }}</el-dropdown-item>
            <el-dropdown-item @click.native="openDialog('group', 'add')">
              {{ $t("operations.group") }}</el-dropdown-item>
            <el-dropdown-item @click.native="openDialog('clone', 'add')">
              {{ $t("operations.clone") }}</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <!-- 编辑 -->
      <el-button :disabled="showEditBtn" @click="openDialog('edit', 'edit')">
        <i class="iconfont icon-bianji2"></i>
        {{ $t("operations.edit") }}
      </el-button>
      <!-- 启动 -->
      <el-button :disabled="!(chosenItem.id && chosenItem.status !== 'Running')">
        <i class="iconfont icon-kaishi"></i>
        {{ $t("operations.start") }}
      </el-button>
      <!-- 停止 -->
      <el-button :disabled="!(chosenItem.id && chosenItem.status !== 'Not Running')">
        <i class="iconfont icon-tingzhi1"></i>
        {{ $t("operations.stop") }}
      </el-button>
      <!-- 清理 -->
      <el-button :disabled="!chosenItem.id">
        <i class="iconfont icon-yijianqingli"></i>
        {{ $t("operations.cleanup") }}
      </el-button>
      <!-- 删除 -->
      <el-popconfirm class="del-btn" :confirm-button-text="$t('common.confirm')"
        :cancel-button-text="$t('common.cancel')" @confirm="handleDelResources" :title="$t('operations.confirmDelete')">
        <template #reference>
          <el-button :disabled="!chosenItem.id">
            <i class="iconfont icon-shanchukai"></i>
            {{ $t("operations.delete") }}
          </el-button>
        </template>
      </el-popconfirm>
      <!-- 关系 -->
      <el-dropdown>
        <el-button :disabled="!(chosenItem.id && chosenItem.id !== 'ms-drbd' && chosenItem.type !== 'clone')">
          <i class="iconfont icon-guanxitu"></i>
          {{ $t("operations.relation") }}
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item>
              <span @click="handleClickRelation('location')">
                {{ $t("operations.location") }}</span>
            </el-dropdown-item>
            <el-dropdown-item>
              <span @click="handleClickRelation('colocation')">
                {{ $t("operations.coop") }}</span>
            </el-dropdown-item>
            <el-dropdown-item>
              <span @click="handleClickRelation('order')">
                {{ $t("operations.order") }}</span>
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>

    </div>

    <div class="header-right">
      <!-- 刷新 -->
      <el-button class="operations" @click.native="refreshResources">
        <i class="iconfont icon-shuaxin"></i>
        {{ $t("operations.refresh") }}
      </el-button>
    </div>

    <!-- dialog -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" :width="dialogWidth"
      :before-close="handleDialogClose">
      <order v-if="dialogType === 'order'" @cancel="handleDialogClose" />
      <location v-if="dialogType === 'location'" @cancel="handleDialogClose" />
      <colocation v-if="dialogType === 'colocation'" @cancel="handleDialogClose" />
      <add-or-edit-rsc ref="ezDialog" v-if="dialogType === 'add_or_edit'" @refresh="refreshResources"
        @cleanSelecting="cleanSelets" @cancel="handleDialogClose" />
    </el-dialog>
  </div>
</template>
<script>
import {
  easyRequest,
  deleteItems,
  getResourceRelation,
} from "@/api/resource";
import Order from './order.vue';
import Location from './location.vue';
import Colocation from './colocation.vue';
import AddOrEditRsc from './addOrEditRsc.vue';

export default {
  props: ["nodeLists", "chosenItem"],
  components: {
    Order,
    Location,
    Colocation,
    AddOrEditRsc,
  },
  data() {
    return {
      dialogWidth: '600px',
      dialogTitle: '',
      dialogType: '',
      dialogVisible: false,
    }
  },
  computed: {
    //  DRBD主从资源及其子资源不支持编辑操作，类型为bundle的资源不可编辑
    showEditBtn() {
      if (!this.chosenItem.id || (this.chosenItem.id === 'ms-drbd' || this.chosenItem.id === 'drbd-ps:0' || this.chosenItem.id === 'drbd-ps:1' || this.chosenItem.type === 'bundle')) {
        return true;
      } else {
        return false;
      }
    }
  },
  methods: {
    getNodeList() {
      this.nodeList = JSON.parse(JSON.stringify(this.nodeLists));
      this.$forceUpdate();
    },
    cleanSelets() {
      this.$emit("clear");
    },
    // 添加/编辑
    openDialog(type, action) {
      this.dialogTitle =
        action == "add"
          ? this.$t("dialog.add")
          : this.$t("dialog.edit");
      this.dialogType = 'add_or_edit';
      this.dialogVisible = true;
      this.dialogWidth = '700px';
      this.$refs.ezDialog.handleDialogOpen(type, action);
    },
    // // 添加
    // handleClickAdd(type) {
    //   console.log('添加', type);

    // },
    // // 编辑
    // handleClickEdit() {
    //   console.log('编辑')
    // },

    // 启动、停止、清理
    handleOperate(action) {
      let data = {};
      data.id = this.chosenItem.id;
      data.action = action;

      easyRequest(data).then(() => {
        this.refreshResources();
        this.$message.success("resource " + action + " success");
      });
    },
    // 关系
    handleClickRelation(type) {
      console.log('关系 type', type)
    },
    handleClickRelation(str) {
      this.getNodeList();

      //判断传来的值是否与tableData的id相同，相同置为disabled
      function getSelectChildrenData(data) {
        this.resources_id = [];
        for (const item of this.$store.state.rscs) {
          if (item.id == data.rsc_id || item.type == "clone") {
            continue;
          }
          this.resources_id.push({
            id: item.id,
          });
        }
        for (const key in data) {
          if (key == "rsc_id" || data[key].length == 0) continue;
          for (let i in data[key]) {
            for (const j in this.resources_id) {
              if (data[key][i] == this.resources_id[j].id) {
                this.resources_id[j].disabled = true;
              }
            }
          }
        }
      }

      // let url = "/resources/" + this.chosenItem.id + "/relations/" + str;
      getResourceRelation({ id: this.chosenItem.id, action: str }).then((res) => {
        switch (str) {
          case "colocation":
            this.rscColocation = res.data.data;
            getSelectChildrenData(this.rscColocation);
            // this.rscColocation = colocation;
            this.dialogTitle = this.$t('operations.coop');
            this.dialogType = 'colocation';
            this.dialogVisible = true;
            break;
          case "order":
            this.rscOrder = res.data.data;
            if (this.rscOrder) {
              getSelectChildrenData(this.rscOrder);
            }
            this.dialogTitle = this.$t('operations.order');
            this.dialogType = 'order';
            this.dialogVisible = true;
            break;
          default:
            let key = "";
            for (let item in this.nodeList) {
              if (item === "0") {
                key = "Master Node";
              } else {
                key = `Slave ${item}`;
              }
              this.rscLocation[key] = [];
            }
            //将从接口获取到的值赋给rscLocation
            if (res.data.data.node_level) {
              res.data.data.node_level.map((item) => {
                for (const key in this.rscLocation) {
                  if (item.level === key) {
                    this.rscLocation[key].push(item.node);
                  }
                }
                //循环遍历node是否与nodeList的id相同，相同则置nodeList为disable
                for (const i in this.nodeList) {
                  if (item.node === this.nodeList[i].id) {
                    this.nodeList[i].disabled = true;
                  }
                }
              });
            }
            this.dialogTitle = this.$t('operations.location');
            this.dialogType = 'order';
            this.dialogVisible = true;
            break;
        }
      });
    },
    // 删除资源
    handleDelResources() {
      let id = this.chosenItem.id;

      deleteItems(id).then(() => {
        this.refreshResources();
        this.$message.success("resource delete success");
      });
    },
    // 刷新
    refreshResources() {
      this.$emit("refreshData");
    },

    // dialog 关闭
    handleDialogClose() {
      this.dialogTitle = '';
      this.dialogType = '';
      this.dialogVisible = false;

      this.refreshResources();
    }
  }
}

</script>
<style lang="scss" scoped>
.header-oper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.drop-btn {
  margin-right: 10px;
}

.del-btn {
  margin-right: 10px;
  margin-left: 10px;
}
</style>